package cn.zero.api.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.Callable;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.zero.service.WechatService;


@RestController
@RequestMapping("/api/wechat")
public class WechatAPIController extends BaseAPIController {

	@Autowired
	private WechatService wechatService;

	@PostMapping("/getJSSDKData")
	public Object getWechatSignature(
			@RequestParam("appid") String appid,
			@RequestParam("nonceStr") String nonce_str,
			@RequestParam("timestamp") String timestamp, @RequestParam("url") String url, HttpServletRequest request)
			throws IOException {
		return asynSuccess(() -> {
			JSONObject json = new JSONObject();
			json.put("appId", wechatService.getAppId());
			json.put("signature", wechatService.getSignature(appid, nonce_str, timestamp, url));
			return json;
		});
	}

	/**
	 * 获取微信授权url -
	 * 
	 * @param state
	 * @param url
	 * @param authorize
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/getWechatAuthorizeUrl")
	public Object getWechatAuthorizeUrl(@RequestParam(value = "url", required = false) String url,
			@RequestParam(value = "state", required = false, defaultValue = "") String state,
			@RequestParam(value = "authorize", required = false, defaultValue = "false") boolean authorize)
			throws Exception {
		return success(wechatService.getWechatAuthorizeUrl(state, url, authorize));
	}

	@RequestMapping("/process")
	public Object process(
			@RequestParam(value = "appid", required = false) String appid,
			@RequestParam(value = "echostr", required = false) String echostr,
			@RequestParam(value = "signature", required = false) String signature,
			@RequestParam(value = "timestamp", required = false) String timestamp,
			@RequestParam(value = "nonce", required = false) String nonce, HttpServletRequest request)
			throws Exception {
		Callable<String> res = () -> {
			if (!StringUtils.isEmpty(echostr) && wechatService.checkSignature(signature, timestamp, nonce)) {
				return echostr;
			}
			InputStream inputStream = request.getInputStream();
			SAXReader reader = new SAXReader();
			Document document = reader.read(inputStream);
			return wechatService.processRequest(appid, document);
		};
		return res;
	}

}
